package com.haven123.cloudapp.websocket;

import com.haven123.cloudapp.websocket.feign.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;


@Component
@ServerEndpoint("/ws/{userId}")
public class WebSocketServer {

    @Autowired
    private UserService userService;
    public static final AtomicInteger atomicInteger= new AtomicInteger(0);
    public Session session;

    @OnOpen
    public void onOpen(@PathParam("userId")Long userId, Session session){
        System.out.println(userId);
        int i = atomicInteger.incrementAndGet();
        System.out.println(i);
        this.session=session;
        App.map.put(userId,this);

        try {
            session.getBasicRemote().sendText("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @OnClose
    public void onClose(Session session){
        atomicInteger.decrementAndGet();
        System.out.println("onclose");
    }
    @OnMessage
    public void onMessage(String message,Session session){
        try {
            System.out.println(message);
            session.getBasicRemote().sendText("已经收到");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
